package cn.johnyu.config;

import cn.johnyu.filter.CookieCheckFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private CookieCheckFilter cookieCheckFilter;

//    自定义的AuthenticationManager,用它来替换框架原生的AuthenticationManager，进而实现自定义的登录逻辑
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
//    因为框架原生提供的AuthenticationManager可以读取spring.security.user.name的配置，
//    但是我们这里使用了自定义的AuthenticationManager，不能直接读取到配置（会导致stackoverflow）,
//    所以需要手动创建一个UserDetailsService的Bean
//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
////        两种不同的创建用户的方式
//        UserDetails user = User.withDefaultPasswordEncoder()
//                .username("admin")
//                .password("123")
//                .roles("ADMIN")
//                .build();
//
//        userDetailsManager.createUser(User.withDefaultPasswordEncoder()
//                .username("john")
//                .password("123")
//                .roles("USER")
//                .build());
//
//        userDetailsManager.createUser(user);
//
//        return userDetailsManager;
//    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .formLogin(form -> form.disable())
                .httpBasic(basic -> basic.disable())
                .logout(logout -> logout.disable()) // 以上四行：禁用默认的UsernamePasswordAuthenticationFilter，不再使用表单方式
                .authorizeRequests(auth -> {
                    auth.requestMatchers("/login", "/logout").permitAll() //放行自定义的登录和登出接口
                            .requestMatchers("/books").hasAnyRole("ADMIN") //只有ADMIN角色可以访问/books接口
                            .anyRequest().authenticated();//其他请求都需要认证
                });
        http.addFilterBefore(cookieCheckFilter, UsernamePasswordAuthenticationFilter.class); // 添加自定义过滤器（CookieCheckFilter）到UsernamePasswordAuthenticationFilter之前

        return http.build();
    }


}
